<template>
  <div>
    <van-index-bar>
        <div v-for="(itemFa,indexFa) in lettersList" :key="indexFa">
            <van-index-anchor :index="itemFa.letter" />
            <van-cell :title="item.label" v-for="(item,index) in itemFa.list" :key="index"/>
        </div>
    </van-index-bar>
  </div>
</template>

<script>
import { citylist } from '@/api/user'
const pinyin = require('js-pinyin')
export default {
  data () {
    return {
      lettersList: []
    }
  },
  async  created () {
    const { body } = await citylist()
    console.log(body)

    body.forEach(item => { item.pinyin = pinyin.getFullChars(item.label) })
    const provice = {}
    body.forEach((item) => {
      const Initials = item.pinyin[0].toUpperCase()
      // 如果对象里有当前字母项则直接 push 一个对象,如果没有则创建一个新的键并赋值;
      if (provice[Initials]) {
        provice[Initials].push(item)
      } else {
        provice[Initials] = [item]
      }
    })
    // 将数据转为数组，并按字母顺利排列
    this.filterData = []
    for (const key in provice) {
      const obj = { letter: key, list: provice[key] }
      this.filterData.push(obj)
    }
    this.filterData.sort((a, b) => { return a.letter.localeCompare(b.letter) })
    // 为索引字符数组赋值
    this.indexList = []
    this.filterData.forEach(item => this.indexList.push(item.letter))
    console.log('filterData', this.filterData)
    this.lettersList = this.filterData
  }
}

</script>

<style>

</style>
